package com.wlcb.jpower.chat.message.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wlcb.jpower.constant.RedisEunm;
import com.wlcb.jpower.module.common.redis.RedisUtil;
import com.wlcb.jpower.utils.RedisHelpUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: liwenfei
 * @version: v1.0
 * @time: 2021/4/6 14:06
 * @desc: 接收订阅通知回调
 */
@Component
public class SubscribeMsgPopupHandler extends AbstractHandler {
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {
        logger.debug("接收订阅通知的回调：{}", wxMpXmlMessage.toString());
        String appId = map.get("appId").toString();
        RedisUtil redisUtil = RedisHelpUtils.getRedisUtil();
        JSONArray array = toSubList(wxMpXmlMessage);
        for (Object object : array) {
            JSONObject result = JSONObject.parseObject(object.toString());
            String isAccept = result.getString("SubscribeStatusString");
            String templateId = result.getString("TemplateId");
            if ("accept".equals(isAccept)) {
                redisUtil.set(RedisEunm.SUB.getKeyPrefix() + appId + ":" + templateId + ":" + wxMpXmlMessage.getFromUser(), 0);
            } else {
                redisUtil.remove(RedisEunm.SUB.getKeyPrefix() + appId + ":" + templateId + ":" + wxMpXmlMessage.getFromUser());
            }
        }
        return null;
    }

    private JSONArray toSubList(WxMpXmlMessage wxMpXmlMessage) {
        JSONObject jsonObject = JSONObject.parseObject(wxMpXmlMessage.toString());
        Map allFieldsMap = JSONObject.parseObject(jsonObject.getString("allFieldsMap"), Map.class);
        String subscribeMsgPopupEvent = allFieldsMap.get("SubscribeMsgPopupEvent").toString();
        JSONObject subObj = JSONObject.parseObject(subscribeMsgPopupEvent);
        String list = subObj.getString("List");
        return JSONObject.parseArray(list);
    }
}
